package com.wujunshen.algorithm.leetcode.depth.first.search;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/25 17:00<br>
 */
public class 岛屿的最大面积 {
  public int maxAreaOfIsland(int[][] grid) {
    int area = 0;
    for (int i = 0; i < grid.length; i++) {
      for (int j = 0; j < grid[0].length; j++) {
        if (grid[i][j] == 1) {
          area = Math.max(dfs(grid, i, j), area);
        }
      }
    }
    return area;
  }

  private int dfs(int[][] grid, int i, int j) {
    if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 0) {
      return 0;
    }
    grid[i][j] = 0;
    int area = 1;
    area += dfs(grid, i + 1, j);
    area += dfs(grid, i, j + 1);
    area += dfs(grid, i - 1, j);
    area += dfs(grid, i, j - 1);

    return area;
  }
}
